package base

import (
	"gitee.com/slion/infra"
	_ "github.com/go-sql-driver/mysql"
	"github.com/tietang/dbx"
	"time"
)

// 数据库实例
var dbxDatabase *dbx.Database

// 对外暴露获取数据库实例的方法
func DbxDatabase() *dbx.Database{
	return dbxDatabase
}

type DbxDatabaseStarter struct {
	infra.BaseStarter
}

func (dbStarter *DbxDatabaseStarter) Setup(ctx infra.StartContext){

	config := ctx.GetProps()
	settings := dbx.Settings{
		DriverName:      config.GetDefault("mysql.driver", "mysql"),
		User:            config.GetDefault("mysql.user", "root"),
		Password:        config.GetDefault("mysql.password", ""),
		Database:        config.GetDefault("mysql.database", "test"),
		Host:            config.GetDefault("mysql.host", "127.0.0.1") + ":" + config.GetDefault("mysql.port", "3306"),
		Options: 		 map[string]string{
			"charset":   config.GetDefault("mysql.charset", "utf8"),
			"parseTime": "true",
		},
		ConnMaxLifetime: time.Hour * config.GetDurationDefault("mysql.connMaxLifetime", 7),
		MaxOpenConns:    config.GetIntDefault("mysql.maxOpenConns", 20),
		MaxIdleConns:    config.GetIntDefault("mysql.maxIdleConns", 10),
		LoggingEnabled:  true,
	}

	db, err := dbx.Open(settings)
	if err != nil {
		panic(err)
	}

	err = db.Ping()
	if err != nil {
		panic(err)
	}

	dbxDatabase = db
}